package com.example.repair.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.MapsInitializer;
import com.example.repair.R;
import com.example.repair.base.BaseActivity;
import com.example.repair.base.Presenter.PressenterImpl;
import com.example.repair.base.netWork.Constant;
import com.example.repair.base.netWork.LoginContract;
import com.example.repair.entity.UserLogin;
import com.example.repair.util.SpUtils;
import com.example.repair.util.StringUtils;
import com.example.repair.util.UserPermissionUtil;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity implements LoginContract.IView {

    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.error)
    TextView error;
    @BindView(R.id.login)
    Button login;
    @BindView(R.id.check)
    CheckBox check;

    private Drawable drawables;


    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation.getErrorCode() == 0) {
                aMapLocations = aMapLocation;
//可在其中解析amapLocation获取相应内容。
            }else {
                Toast.makeText(LoginActivity.this, "失败：ErrCode:" + aMapLocation.getErrorCode() + ", errInfo:" + aMapLocation.getErrorInfo(), Toast.LENGTH_SHORT).show();
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e("AmapError","location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }


        }
    };

    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    private PressenterImpl pressenter;
    private AMapLocation aMapLocations;

    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);

        pressenter = new PressenterImpl();
        pressenter.attachView(LoginActivity.this);

        MapsInitializer.updatePrivacyShow(LoginActivity.this,true,true);
        MapsInitializer.updatePrivacyAgree(LoginActivity.this,true);

        String uid = SpUtils.getString(this, "uid");
        if (uid != null && !uid.equals("")) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        }

    }

    final int LOCATION_CODE=200;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initData() {
        password.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                // et.getCompoundDrawables()得到一个长度为4的数组，分别表示左右上下四张图片
                Drawable drawable = password.getCompoundDrawables()[2];
                //如果右边没有图片，不再处理
                if (drawable == null) {
                    return false;
                }
                //如果不是按下事件，不再处理
                if (motionEvent.getAction() != MotionEvent.ACTION_UP) {
                    return false;
                }
                if (motionEvent.getX() > password.getWidth() - password.getPaddingRight() - drawable.getIntrinsicWidth()) {
                    showOrHide(password);
                }
                return false;
            }
        });

        //获取权限（如果没有开启权限，会弹出对话框，询问是否开启权限）
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //请求权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
        } else {
            getstation();
        }



    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case LOCATION_CODE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    // 权限被用户同意。
                    // 执形我们想要的操作
                    getstation();
                } else {
                    Toast.makeText(this, "没有定位将无法给您订单！", Toast.LENGTH_SHORT).show();
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
                }
            }
        }
    }

    private void getstation() {

        //初始化定位
        try {
            mLocationClient = new AMapLocationClient(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
//初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);


        //获取一次定位结果：
//该方法默认为false。
        mLocationOption.setOnceLocation(true);

//获取最近3s内精度最高的一次定位结果：
//设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);

        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否允许模拟位置,默认为true，允许模拟位置
        mLocationOption.setMockEnable(false);

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
//启动定位
        mLocationClient.startLocation();

    }


    @OnClick({R.id.login, R.id.forget, R.id.regist, R.id.xieyi, R.id.yinsi})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.login:
                String text_phone = phone.getText().toString();
                String text_pass = password.getText().toString();

                if (text_phone == null || text_phone.equals("") || text_pass == null || text_pass.equals("")) {
                    Toast.makeText(this, "请检查数据", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (StringUtils.isRegistMobileNO(text_phone)) {
                    Toast.makeText(this, "手机号格式错误", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (StringUtils.isRegistMobileNO1(text_pass)) {
                    Toast.makeText(this, "密码格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!check.isChecked()){
                    Toast.makeText(this, "请阅读并同意益修家电用户协议和隐私政策", Toast.LENGTH_SHORT).show();
                    return;
                }
                Map<String, String> map = new HashMap<>();
                map.put("user_login", text_phone);
                map.put("user_pass", text_pass);
                map.put("lng", aMapLocations.getLongitude()+"");
                map.put("lat", aMapLocations.getLatitude()+"");
                map.put("token", Constant.TOKEN);

                pressenter.sendMessage(this, Constant.login, map, UserLogin.class);

                break;
            case R.id.forget:
                intent=new Intent(LoginActivity.this,ForgetActivity.class);
                startActivity(intent);
                break;
            case R.id.regist:
                intent=new Intent(LoginActivity.this,RegistActivity.class);
                startActivity(intent);
                break;
            case R.id.xieyi:
                intent=new Intent(LoginActivity.this,WebActivity.class);
                intent.putExtra("name","用户协议");
                startActivity(intent);
                break;
            case R.id.yinsi:
                intent=new Intent(LoginActivity.this,WebActivity.class);
                intent.putExtra("name","用户隐私");
                startActivity(intent);
                break;
        }
    }


    private void showOrHide(EditText etPassword) {
        //记住光标开始的位置
        int pos = etPassword.getSelectionStart();
        if (etPassword.getInputType() != (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD)) {//隐藏密码
            drawables = getResources().getDrawable(R.mipmap.eyen);
            drawables.setBounds(0, 0, drawables.getMinimumWidth(), drawables.getMinimumHeight());
            etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        } else {//显示密码
            drawables = getResources().getDrawable(R.mipmap.eyes);
            drawables.setBounds(0, 0, drawables.getMinimumWidth(), drawables.getMinimumHeight());
            etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        }
        etPassword.setCompoundDrawablesWithIntrinsicBounds(null, null, drawables, null);
        etPassword.setSelection(pos);
    }



    @Override
    public void requesta(Object data) {
        if (data instanceof UserLogin){
            UserLogin userLogin= (UserLogin) data;
            if (userLogin.getCode()==1){
                SpUtils.saveString(LoginActivity.this,"uid",userLogin.getData().getUid()+"");
                Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                startActivity(intent);
                finish();
            }else {
                Toast.makeText(this, userLogin.getMessage(), Toast.LENGTH_SHORT).show();
            }

        }
    }

    @Override
    public void fail(String error) {

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
        mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }
}
